package com.xqls.biz.impl;

import com.xqls.bean.*;
import com.xqls.biz.CompanyBiz;
import com.xqls.biz.DictionaryBiz;
import com.xqls.dal.model.Company;
import com.xqls.dal.model.DeviceSchema;
import com.xqls.dal.model.DeviceSchemaExample;
import com.xqls.dal.model.FluggasDischargeRealdata;
import com.xqls.dal.service.DeviceSchemaMapper;
import com.xqls.dal.service.IntakeRealdataMapper;
import com.xqls.service.*;
import com.xqls.util.*;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CompanyBizImpl implements CompanyBiz{
	
	private static Logger logger = Logger.getLogger(CompanyBizImpl.class);

	@Autowired private CompanyService companyService;
	@Autowired private DictionaryBiz dictionaryBiz;
	@Autowired private UserService userService;
    @Autowired private TransactionTemplate transactionTemplate;
	@Autowired private IntakeRealdataService intakeRealdataService;
	@Autowired private DischargeRealdataService dischargeRealdataService;
	@Autowired private RainwaterDischargeRealdataService rainwaterDischargeRealdataService;
	@Autowired private PublicStormwaterRealdataService publicStormwaterRealdataService;
	@Autowired private FluggasDischargeRealdataService fluggasDischargeRealdataService;
	@Autowired private DeviceSchemaMapper deviceSchemaMapper;


	@Value("${deviceSchema}")
	private String deviceSchema;

	@Override
	public CommonResult edit(CompanyBean bean){
		CommonResult result = new CommonResult();
		boolean success = false;
		try {
			if(bean != null){
				success=transactionTemplate.execute(new TransactionCallback<Boolean>() {
					@Override
					public Boolean  doInTransaction(TransactionStatus status) {
						boolean success = false;
						String tentNo=ContextUtil.getTentNo();
						int type=bean.getDeviceType();
						DeviceSchema deviceSchemaBean=new DeviceSchema();
						deviceSchemaBean.setDeviceNo(bean.getDeviceNo());
						deviceSchemaBean.setDeviceType(bean.getDeviceType());
						deviceSchemaBean.setSchemaNo(tentNo);
						if(bean.getCompanyId() != null){
							  companyService.update(bean);
							//切换数据库  device_schema  把设备编号存 进去 再切回来
//							try{
//								ContextUtil.setTentNo(deviceSchema);
//								DeviceSchemaExample example=new  DeviceSchemaExample();
//								example.createCriteria().andDeviceNoEqualTo(bean.getDeviceNo());
//								deviceSchemaMapper.updateByExample(deviceSchemaBean,example);
//								success=true;
//							}finally {
//								ContextUtil.setTentNo(tentNo);
//							}

						}else{
							 companyService.add(bean);
							  if(type==2){
								IntakeRealdataBean intakeRealdataBean = new IntakeRealdataBean();
								intakeRealdataBean.setDeviceNo(bean.getDeviceNo());
								intakeRealdataBean.setNetwork("离线");
								intakeRealdataService.insertIntakeRealdata(intakeRealdataBean);
							}else if(type==3){
								  DischargeRealdataBean dischargeRealdataBean=new DischargeRealdataBean();
								  dischargeRealdataBean.setDeviceNo(bean.getDeviceNo());
								  dischargeRealdataBean.setNetwork("离线");
								  dischargeRealdataService.insertDischargeRealdata(dischargeRealdataBean);
							  }else if(type==4){
								  RainwaterDischargeRealdataBean rainwaterDischargeRealdataBean=new RainwaterDischargeRealdataBean();
								  rainwaterDischargeRealdataBean.setDeviceNo(bean.getDeviceNo());
								  rainwaterDischargeRealdataBean.setNetwork("离线");
								  rainwaterDischargeRealdataService.insertRainwaterDischargeRealdataList(rainwaterDischargeRealdataBean);
							  }else if(type==5){
								  PublicStormwaterRealdataBean publicStormwaterRealdataBean=new PublicStormwaterRealdataBean();
								  publicStormwaterRealdataBean.setDeviceNo(bean.getDeviceNo());
								  publicStormwaterRealdataBean.setNetwork("离线");
								  publicStormwaterRealdataService.insertPublicStormwaterRealdata(publicStormwaterRealdataBean);
							  }else if(type==6){
							  	 FluggasDischargeRealdataBean fluggasDischargeRealdataBean=new FluggasDischargeRealdataBean();
								  fluggasDischargeRealdataBean.setDeviceNo(bean.getDeviceNo());
								  fluggasDischargeRealdataBean.setNetwork("离线");
							  	 fluggasDischargeRealdataService.insertRealdata(fluggasDischargeRealdataBean);
							  }
							//切换数据库  device_schema  把设备编号存 进去 再切回来
//							try{
//								ContextUtil.setTentNo(deviceSchema);
//								deviceSchemaMapper.insert(deviceSchemaBean);
//								success=true;
//							}finally {
//								ContextUtil.setTentNo(tentNo);
//							}

						}
						return success;
					}
				});

				result.setIsSuccess(success);
			}
		} catch (Exception e) {
			logger.error("编辑企业异常",e);
		}
		return result;
	}
	

	
	@Override
	public CommonResult removeList(List<Integer> keys){
		CommonResult result = new CommonResult();
		boolean success = false;
		try {
			if(keys.size()>0){
				success=transactionTemplate.execute(new TransactionCallback<Boolean>() {
     		@Override
			 	public Boolean  doInTransaction(TransactionStatus status) {
				boolean success = false;
				List<String> deviceNos = companyService.getList(keys);
				if(deviceNos!=null)
					{
						  intakeRealdataService.deleteBydeviceNo(deviceNos);
						//  String tentNo = ContextUtil.getTentNo();
//							try {
//								ContextUtil.setTentNo(deviceSchema);
//								DeviceSchemaExample example = new DeviceSchemaExample();
//								example.createCriteria().andDeviceNoIn(deviceNos);
//								deviceSchemaMapper.deleteByExample(example);
//								success=true;
//							} finally {
//								ContextUtil.setTentNo(tentNo);
//							}
					}
				companyService.deleteList(keys);
				return success;
					}
				});

			}
			result.setIsSuccess(success);
		} catch (Exception e) {
			logger.error("批量删除企业异常",e);
		}
		return result;
	}
	
	@Override
	public CompanyBean queryByKey(Integer key){
		CompanyBean bean = null;
		try {
			bean = companyService.queryByKey(key);
		} catch (Exception e) {
			logger.error("根据主键查询企业异常",e);
		}
		return bean;
	}
	
	@Override
	public CommonResult queryByDevice(String deviceNo){
		CommonResult  result = new CommonResult();
		try {
			result = companyService.queryByDeviceNo(deviceNo);
		} catch (Exception e) {
			logger.error("根据设备编号查询企业异常",e);
		}
		return result;
	}
	
	@Override
	public List<Map<String, Object>> queryByBlock(String blockUrl,Integer deviceType){
		Map<String, Object> map = new HashMap<String, Object>();
		List<Map<String, Object>> beans = null;
		try {
			map.put("blockUrl", blockUrl);
			map.put("deviceType", deviceType);
			beans = companyService.queryByMap(map);
		} catch (Exception e) {
			logger.error("根据条件查询企业异常",e);
		}
		return beans;
	}
	
	
	
	@Override
	public CommonResult queryByCommpage(CommonPage commonPage, HttpServletRequest request, HttpServletResponse response){
		CommonResult result = new CommonResult();
		try {
			List<Map<String,Object>> companyList = companyService.queryByMap(commonPage.pageToMap());
			int curr=commonPage.getCurr();
			for (int i=0;i<companyList.size();i++){
				if(curr==1){
					companyList.get(i).put("viewId",i+1);
				}else{
					companyList.get(i).put("viewId",i+1+((curr-1)*15));
				}

			}
			commonPage.setPageData(companyList);
			Map<String,Object> showMap=new HashMap<String,Object>();
			showMap.put("companyList",commonPage.getPageData());
			Map<Integer, String> companyTypeMap = dictionaryBiz.queryDictionaryByParent(
					  DictionaryEnums.COMPANY_TYPE.getCode());
			showMap.put("companyTypeMap",companyTypeMap);
			commonPage.setHtml(VelocityUtil.getHtmlByMap("company/companyListData.vm",showMap,request,response,request.getSession().getServletContext()));
			result.setIsSuccess(true);
		} catch (Exception e) {
			logger.error("分页条件查询操作记录异常",e);
		}
		return result;
	}

	@Override
	public List<Company> getList(DictionaryEnums dictionaryEnums) {
		List<Company> companyList=null;
		try {
			companyList=this.companyService.getList(dictionaryEnums.getCode());
		} catch (Exception e) {
			logger.error("查询企业异常",e);
		}
		return companyList;
	}
	
	@Override
	public List<Company> getList() {
		List<Company> companyList=null;
		try {
			companyList=this.companyService.getList();
		} catch (Exception e) {
			logger.error("查询企业异常",e);
		}
		return companyList;
	}
}
